if(!window.js_config_loaded){
	window.location.reload();
}
try{
	var app = angular.module('main', []);
}catch(err){
	window.location.reload();
}
app.config(function($sceDelegateProvider) {
   $sceDelegateProvider.resourceUrlWhitelist([
       'self',
	   'http://mi.gdt.qq.com/**',
	   'https://mi.gdt.qq.com/**',
       window.config.attachment_url+'**',
	   window.config.attachment_rooturl+'**'
   ]);
});
app.controller('JinyunCtrl', ['$scope','$sce','$compile', function($scope,$sce,$compile){
	$scope.main=window.config.main;
	$scope.username=window.config.username;
	$scope.header=false;
	$scope.func={};
	$scope.unitfunc={};
	$scope.page=false;//保证第一次访问页面时不会额外增加历史记录
	$scope.historys=[];
	$scope.before_post=[];
	$scope.default_area={};//初始化默认位置对象
	$scope.choose_titles={};//初始化数据选择组件要用到的名称对象集
	var made_page_js=(window.config.os=='windows')?'made_page':'made_page_mobile';
	require(['base64','tool',made_page_js],function(base64,tool,made_page){
	$scope.base64=base64;
	$scope.tool=tool;
	$scope.framess={};
	if($scope.main.framess){
		$scope.framess.core=$scope.main.framess;
		$scope.current_menu='core';
	}
	
	//系统菜单相关函数
	//值切换
	$scope.toogle=function(data,field,values){
		if(values && Array.isArray(values)){
			if(data[field]==values[0]){
				data[field]=values[1];
			}else{
				data[field]=values[0];
			}
		}else{
			if(data[field]){
				data[field]=false;
			}else{
				data[field]=true;
			}
		}
	}
	
	$scope.config=function(key){
		return window.config[key];
	}
	$scope.set_lang=function(lang){
		$scope.main.show_lang=lang;
		$scope.get('core/tools.set_lang//lang='+lang,function(res){
			
		});
	}
	$scope.check_show_lang=function(ch,en){
		//console.log('$scope.show_lang');console.log($scope.show_lang);
		if(!en && ch && typeof(ch)=='string'){
			var index=ch.indexOf('_');
			if(index>0){
				en=ch.slice(index+1);
				ch=ch.slice(0,index);
			}
		}
		if($scope.main.show_lang=='en' && en){
			//console.log('check_show_lang en');
			return en;
		}else{
			//console.log('check_show_lang ch');
			return ch;
		}
	}
	$scope.getrandom=function(min,max){
		min=min?min:1;
		max=max?max:5;
		var num=random() * (max - min)
		num=parseInt(num) + min;
		return num
	}
	//根据查询数组拼接query以便发起get请求
	$scope.made_query=function(params){
		//console.log('调用栈');console.trace();
		var pms=clone(params);
		for(var k in pms){
			if(typeof(pms[k])=='object'){
				pms[k]=base64.encode(angular.toJson(pms[k]),window.config.base_key_str);
			}else if(typeof(pms[k])=='string'){
				if(pms[k].indexOf("/") != -1 || pms[k].indexOf("&") != -1){
					pms[k] = encodeURIComponent(pms[k]);
				}
			}
		}
		return tool.made_query(pms);
	}
	$scope.access_json=function(json,query,pagetitle){
		if(!json){
			return false;
		}
		if($.isFunction(json)){
			json();
			return true;
		}
		if(json=='goback'){
			$scope.goback();
			return true;
		}
		if(typeof(json)!='object'){
			if(json.slice(0,4)=='http' || json.slice(0,11)=='./index.php'){
				//URL地址直接访问
				window.location.href=json;
				return true;
			}else{
				json=$scope.links(json);
			}
		}else{
			pagetitle=pagetitle?pagetitle:json.title
		}
		//兼容新型URL提交
		if(json.action && json.action.indexOf('/')>=0){
			json=$scope.links(json.action);
		}
		//console.log('access_json');console.log(json);
		if(query){
			if(!json.query){
				json.query=query;
			}else{
				json.query+='&'+query;
			}
		}
		var url=location.href;
		if(url.indexOf('?')>0 && json.action && !json.op && !json.query && window.config.username && window.config.this=='manage' && false){//该功能暂时取消			
			var data=url.split('?');
			//如果是旧插件页面，更新地址前先将要访问的页面参数传回后台存入session
			var post={'action':json.action};
			if(json.plugin){
				post.plugin=json.plugin;
			}
			if(json.action=='basic.module_home' && !post.plugin){
				post.plugin=$scope.page.plugin;
			}
			post=angular.toJson(post);
			post=base64.encode(post,window.config.base_key_str);
			var postdata={'plugin':'core','action':'tools.session','postdata':post,'nosession':1};
			$scope.ajax(postdata,'',function(result){
				if(result=='success'){
					location.href=data['0'];
					return true;
				}else{
					$scope.message(result,'error');
				}
			});
		}else{			
			$scope.access(json.op,json.query,json.action,json.html,pagetitle,json.plugin,json.nohis);
		}
	}
	$scope.tomedia=function(url,root){
		if(!url || typeof(url)!='string'){
			return false;
		}
		if(url.slice(0,4)=='http' || url.slice(0,2)=='//'){
			//url = url.replace('https:', '');
			//url = url.replace('http:', '');
			return url;
		}else if(url.slice(0,16)=='../core/resource'){
			return url;
		}else if(url.slice(0,10)=='../addons/'){
			return url;
		}else{
			var dd=url.split('.');
			if(dd['1']=='html' && !root){
				var file_url = window.config.attachment_url+url+'?v='+window.config.urlargs;
			}else if(dd['1']=='html' && root){
				var file_url = window.config.root_at+url+'?v='+window.config.urlargs;
			}else if(root){
				var file_url = window.config.root_at+url;
			}else{
				var file_url = window.config.attachment_url+url;
			}
			return file_url;
		}
	}
	$scope.page_loading=function(type){
		if(!type){
			type='show';
		}
		if($('#page-loading').length==0){
			$.get(window.config.siteroot+'core/resource/loading.html?v='+window.config.urlargs,function(loading_html){
				if($('#page-loading').length==0){
					$('body').prepend(loading_html);
				}
				$scope.page_loading(type);
			});
			return;
		}
		if(type=='show'){
			$('#page-loading').show();
		}else{
			$('#page-loading').hide();
		}
	}
	$scope.header_loaded=function(){
		window.wait_header_download=false;
	}
	$scope.insert_html=function(page_html){
		setTimeout(function(){
			if($('#base_template_html').length==0 || window.wait_header_download){
				$scope.insert_html(page_html);
			}else{
				$('#base_template_html').html(page_html);
			}
		},100);
	}
	$scope.access_menu=function(menu){
		if(menu.url){
			scope.access_json(menu.url,'',menu.title);
		}else{
			scope.access_json(menu);
		}
	}
	$scope.active_menu=function(){
		//console.log('active_menu');
		var framess=$scope.framess[$scope.current_menu];
		if(!framess){
			return false;
		}
		var stop=false;
		if(!$scope.frames && framess){
			//后台指定当前高亮
			if($scope.main.frames){
				$scope.frames=$scope.main.frames;
			}else if($scope.framesdiy){
				//console.log('framesdiy');
				$scope.frames=$scope.framesdiy;
			}else{
				$scope.frames=framess[0];
			}
		}
		//先遍历当前菜单
		$scope.frames=$scope.frames?$scope.frames:[];
		angular.forEach($scope.frames.child,function(frame,y){
				if(stop){
					return;
				}
				angular.forEach(frame.child,function(menu,z){
					if(stop){
						return;
					}
					if(menu.url){
						if(typeof(menu.url)=='string'){
							menu.url=$scope.links(menu.url);
						}
						if($scope.show_active(menu.url)){
							stop=true;
						}
					}
				});
		});
		var issetshow=false;
		angular.forEach(framess,function(frames,x){
			if(stop){
				return;
			}
			if(frames.url){
				if(typeof(frames.url)=='string'){
					frames.url=$scope.links(frames.url);
				}
				if($scope.show_active(frames.url)){
					stop=true;
					if($scope.frames!=frames){
						$scope.frames=frames;
					}
					return;
				}
			}
			angular.forEach(frames.child,function(frame,y){
				if(stop){
					return;
				}
				angular.forEach(frame.child,function(menu,z){
					if(stop){
						return;
					}
					if(menu.url){
						if(typeof(menu.url)=='string'){
							menu.url=$scope.links(menu.url);
						}
						if($scope.show_active(menu.url)){
							stop=true;
							if($scope.frames!=frames){
								$scope.frames=frames;
								$scope.frames.child[y].show=true;
								issetshow=true
							}
						}
					}
				});
			});
		});
		if(!$scope.frames){
			$scope.frames=framess[0];
		}
		//打开首个子菜单
		if(!issetshow && $scope.frames && $scope.frames.child && $scope.frames.child[0]){
			$scope.frames.child[0].show=true;
		}
	}
	$scope.show_active=function(a){
		if(!a){
			return false;
		}
		if(typeof(a)!='object'){
			a=$scope.links(a);
		}
		if(a.url){
			var newurl = a.url
			if(typeof(newurl)=='string'){
				if(newurl.slice(0,4)=='http' || newurl.slice(0,11)=='./index.php'){
					newurl=newurl.split('?');
					newurl=newurl[1];
					newurl=$scope.get_hash(newurl);
				}else{
					newurl=$scope.links(newurl);
				}
			}
			if(!newurl.plugin && !newurl.action && !newurl.op){
				return false;
			}
			if(newurl.plugin && $scope.page.plugin!=newurl.plugin){
				return false;
			}
			if(newurl.action && $scope.page.action!=newurl.action){
				return false;
			}
			$scope.pagedata=$scope.pagedata?$scope.pagedata:{}
			if(newurl.op && $scope.page.op!=newurl.op && $scope.pagedata.op!=a.op){
				return false;
			}
			if(newurl.query && $scope.page.query!=newurl.query){
				return false;
			}
		}else{
			if(!a.plugin && !a.action && !a.op){
				return false;
			}
			if(a.plugin && $scope.page.plugin!=a.plugin){
				return false;
			}
			if(a.action && $scope.page.action!=a.action){
				return false;
			}
			$scope.pagedata=$scope.pagedata?$scope.pagedata:{}
			if(a.op && $scope.page.op!=a.op && $scope.pagedata.op!=a.op){
				return false;
			}
			if(a.query && $scope.page.query!=a.query){
				return false;
			}
		}
		
		return true;
	}
	$scope.access=function(op,query,action,html,title,plugin,nohis){
		$scope.scroll_bottom=false;
		$scope.scroll_top=false;
		scroll(0,0);
		if(!op && !action && !query && !plugin){
			return false;
		}
		$scope.before_post=[];
		$scope.main.tabs=[];
		$scope.modal=false;//刷新弹出页面action
		$scope.modalurl=false;
		var is_first=false;
		if(!nohis && !$scope.access_ing){
			var tr=angular.copy($scope.page);
			$scope.historys.push(tr);
			//console.log($scope.historys);
		}else if(!$scope.page){
			$scope.page={};
			is_first=true;
		}
		//console.log('$scope.page');console.log($scope.page);
		$scope.page.op=op || '';
		$scope.page.query=query;
		if(action && $scope.page.action!=action){
			$scope.page.action=action;
		}
		if(!html){
			html=$scope.replace('.','/',$scope.page.action);
		}
		if(html && $scope.page.html!=html){
			$scope.page.html=html;
		}
		if(title && $scope.page.title!=title){
			$scope.page.title=title;
			$(document).attr('title',title);
			//设置页面关键词
			if($scope.page.keywords){
				$("meta[name='keywords']").attr('content', $scope.page.keywords);
			}
			//设置页面描述
			if($scope.page.description){
				$("meta[name='description']").attr('content', $scope.page.description);
			}
		}
		
		if(plugin && $scope.page.plugin!=plugin){
			$scope.page.plugin=plugin;
			$scope.plugin_resource=window.config.siteroot+'addons/'+plugin+'/resource/';
			if(window.config.this=='manage'){
				$scope.menu_tree=[];			
				if($scope.page.plugin!='core' && (!$scope.page.action || $scope.page.action.indexOf('sys.') <0)){
					//访问模块页面，此处加载模块菜单
					var postdata={'plugin':$scope.page.plugin,'action':'basic.module_home','nosession':1,'op':'get_menu'};
					$scope.ajax(postdata,'',function(res){
						$scope.plugin_title=res.title;
						$scope.plugin_icon=res.image;
						$scope.plugin_name=res.plugin_name;
						$scope.child_plugin_name=res.child_plugin;
						$scope.child_plugin_title=res.child_title;
						if(res.menus){
							$scope.plugin_menu=res.menus;
						}else{
							$scope.plugin_menu=[];
						}
						

					},true);
				}
			}
			
		}
		//访问系统页面时将菜单更换为系统菜单，这里注释掉。已在后端指定
		/*if($scope.main.framess && plugin=='core' && action=='account.welcome'){
			$scope.current_menu='core';
		}*/
		if(!$scope.page.plugin || !$scope.page.action){
			if(html && html.slice(0,6)=='../api'){
				//访问兼容页面，设置系统菜单为
				$scope.page.action='basic.module_home';
				$scope.active_menu();
				if(!$scope.header){
					$scope.header='common/header';
				}
				$scope.main.page=html;
				$scope.$evalAsync();
				return true;
			}
			return false;
		}
		
		$scope.main.find_keyword='';
		$scope.page.url='plugin='+$scope.page.plugin+'&action='+$scope.page.action;
		if($scope.page.op){
			$scope.page.url+='&op='+$scope.page.op;
		}
		if($scope.page.query){
			$scope.page.url+='&'+$scope.page.query;
		}
		$scope.page.time=(new Date()).getTime();
		if($scope.page.plugin != window.config.access_json.plugin){
			$scope.get_data(function(accres){
				$scope.page.accpagetype=accres;
			},'','core/tools.get_data/get_accpagetype/pluginname='+$scope.page.plugin,true);
		}
		if(window.config.close_one_page || $scope.page.accpagetype=='close_one_page'){
				window.location.href='./index.php?i='+window.config.uniacid+'&'+$scope.page.url;
				return;
		}else{
				var hash='#/page/'+$scope.page.url;
		}
		var page_url=JSON.stringify($scope.page);
		if(!nohis && !$scope.access_ing){
				window.history.pushState({'page_url':page_url}, "title", hash);
		}else{
				if(!is_first){
					window.history.replaceState({'page_url':page_url}, "title", hash);
				}else{
					window.history.replaceState({'page_url':page_url}, "title", '');
				}
		}
		$scope.access_ing=true;
		$scope.page_loading();
		$('#mainbody').hide();
		$('#base_template_html').html('');
		$scope.main.page=false;
			
		$scope.$evalAsync();
		var postdata={'plugin':$scope.page.plugin,'action':$scope.page.action,'is_access':1};
		if(op){
				postdata.op=op;
		}
		$scope.ajax(postdata,query,function(data){
				$scope.access_ing=false;
				if($scope.main.framess && Array.isArray($scope.main.framess)){
					$scope.active_menu();//高亮菜单
				}
				if(!$scope.header){
					window.wait_header_download=true;
					if(window.config.uid && $scope.main.framess){
						//登陆 
						if(scope.main.template_name=='oldmoban'){
							$scope.header='common/header-old';
						}else{
							$scope.header='common/header';
						}
						
					}else{
						$scope.header='common/header-cms';
					}
				}
				$scope.pagedata=data;
				var page_field=$scope.page.plugin+'.'+$scope.page.html;
				if(window.config.os=='mobile' && window.sharedata){
					window.sharedata.link=window.config.siteroot+window.config.this+'/index.php?i='+window.config.uniacid+'&'+$scope.page.url;
				}
				if($scope.pagedata.sharedata){
					if(!window.sharedata){
						window.sharedata={};
					}
					if($scope.pagedata.sharedata.title){
						window.sharedata.title=$scope.pagedata.sharedata.title;
					}
					if($scope.pagedata.sharedata.link){
						window.sharedata.link=$scope.pagedata.sharedata.link;
					}
					if($scope.pagedata.sharedata.desc){
						window.sharedata.desc=$scope.pagedata.sharedata.desc;
					}
					if($scope.pagedata.sharedata.imgUrl){
						window.sharedata.imgUrl=$scope.pagedata.sharedata.imgUrl;
					}
				}
				//console.log('后端指定页面！');console.log(data);
				//加载成功再获取页面模版
				if($scope.pagedata.htmls){
					if(typeof($scope.pagedata.htmls)=='string' && $scope.pagedata.htmls.slice(0,4)=='url:'){
						//后端指定页面文件地址
						$scope.use_template=false;
						$scope.main.page=$scope.pagedata.htmls.slice(4);
					}else{
						if($scope.pagedata.htmls.type){
							$scope.pagedata.htmls=[$scope.pagedata.htmls];
						}
						if(typeof($scope.pagedata.htmls[0])=='object' && $scope.pagedata.htmls[0]['tabs']){
							$scope.main.tabs=$scope.pagedata.htmls[0]['tabs'];
						}
						$scope.use_template=true;
						var page_html=$scope.made_page($scope.pagedata.htmls,'pagedata');
						//console.log('准备插入页面代码');console.log(page_html);
						if($('#base_template_html').length==0 || window.wait_header_download){
							$scope.insert_html(page_html);
						}else{
							$('#base_template_html').html(page_html);
							//console.log('插入完毕！')
						}
						$scope.start();
					}
				}
				if($scope.pagedata.main_menus){
					$scope.main.menus=$scope.pagedata.main_menus;
				}
				$scope.$evalAsync();
		});
	}
	$scope.sys_html=function(html,sys,template,pluginname){
		var res='';
		if(($scope.page.plugin=='core' || $scope.page.action=='basic.module_home' || sys) && !pluginname){
			if(template){
				if(html=='common/header' && scope.main.template_mg=='oldmoban'){
					html='common/header-old';
				}
				var os=window.config.os;
				if(window.config.main.no_pc){
					os='mobile'
				}
				res=window.config.siteroot+window.config.this+'/templates/default/'+os+'/'+html+'.html?v='+window.config.urlargs;
			}else{
				res=window.config.html+html+'.html?v='+window.config.urlargs;
			}
		}else{
			var os=window.config.os;
			if(window.config.main.no_pc){
				os='mobile'
			}
			if(os=='windows' && window.config.main.pc_temp_name){
				res=window.config.siteroot+'addons/temp/pc/'+window.config.main.pc_temp_name+'/custom/pc/'+html+'.html?v='+window.config.urlargs;
			}else{
				if(!pluginname){
					pluginname=$scope.page.plugin
				}
				res=window.config.siteroot+'addons/'+pluginname+'/'+window.config.this+'/templates/'+os+'/'+html+'.html?v='+window.config.urlargs;
			}
		}
		return res;
	}
	$scope.modal_html=function(html,sys){
		var res='';
		if($scope.modal_plugin=='core' || $scope.page.action=='basic.module_home' || sys){
			res=window.config.html+html+'.html?v='+window.config.urlargs;
		}else{
			res=window.config.siteroot+'addons/'+$scope.page.plugin+'/'+window.config.this+'/templates/'+window.config.os+'/'+html+'.html?v='+window.config.urlargs;
		}
		return res;
	}
	//向后端获取数据
	$scope.get_data=function(tovalue,field,post,async){
		if(typeof(post)!='object'){
			post=$scope.links(post);
		}
		var postdata={plugin:post.plugin,action:post.action,op:post.op,config_this:post.config_this};
		if(!postdata.plugin){
			postdata.plugin=$scope.page.plugin;
		}
		if(!postdata.action){
			postdata.action=$scope.page.action;
		}
		var callback=function(res){
			if(!res.message || res.type!='success'){
				return;
			}
			if($.isFunction(tovalue)){
				tovalue(res.message,field);
			}else{
				tovalue[field]=res.message;
				$scope.$evalAsync();
			}
		}
		async=async?async:false;
		postdata.jy_waytype='getdata';
		$scope.ajax(postdata,post.query,callback,async,true);
		
	}
	$scope.get=function(url,callback){
		if(!url){
			return false;
		}
		$scope.tool.get(url,function(res){
			if($.isFunction(callback)){
				callback(res);
			}
			$scope.$evalAsync();
		});
	}
	//提交post请求，通常用于请求后端执行相关代码，成功后返回成功状态
	$scope.post_json=function(json,data,callback){
		if(!json){
			return false;
		}
		if(typeof(json)!='object'){
			json=$scope.links(json);
		}
		//兼容新型URL提交
		if(json.action && json.action.indexOf('/')>=0){
			var query=json.query?json.query:'';
			json=$scope.links(json.action);
			json.query=json.query?json.query:'';
			json.query +=query;
		}
		if(data){
			json.data=data;
		}
		if(callback){
			json.callback=callback;
		}
		$scope.post(json.data,json.op,json.query,json.callback,json.message,json.action,json.plugin,json.no_hold);
	}
	$scope.modal_post=function(data,op,query,callback,message,action,plugin,no_hold){
		if(!action){
			action=$scope.modal;
		}
		if(!callback){
			callback=function(res){
				$scope.message(res);
				window.bootstrap('#modal_content').modal('hide');
			}
		}
		plugin=plugin || $scope.modal_plugin;
		$scope.post(data,op,query,callback,message,action,plugin,no_hold);
	}
	$scope.post=function(data,op,query,callback,message,action,plugin,no_hold,ismodule){
		if($scope.posting===true){
			//return false;
		}
		$scope.posting=true;
		if(message){
			var next=confirm(message);
			if(!next){
				$scope.posting=false;
				return false;
			}
		}
		if(!no_hold){
			$scope.page_loading();
		}
		if($scope.before_post.length>0){
			$.each($scope.before_post,function(index,func){
				if($.isFunction(func)){
					func();
				}
			});
		}
		if(!data){
			data={};
		}else if(Array.isArray(data)){
			data=clone(data);
		}
		if(data.url_encode){
			data[data.url_encode]=encodeURIComponent(data[data.url_encode]);
		}
		data=angular.toJson(data);
		data=base64.encode(data,window.config.base_key_str);
		var postdata={'action':$scope.page.action,'plugin':$scope.page.plugin,'postdata':data};
		if(op && op.indexOf('/')>=0){
			//统一URL格式的页面写法
			var url=$scope.links(op);
			action=url.action;
			op=url.op;
			plugin=url.plugin;
			if(url.query){
				if(query){
					query+='&'+url.query;
				}else{
					query=url.query;
				}
			}
		}
		if(action){
			postdata.action=action;
		}
		if(plugin){
			postdata.plugin=plugin;
		}
		if(op){
			postdata.op=op;
		}
		if(ismodule){
			postdata.ismodule=ismodule;
		}
		//定义请求方式
		postdata.jy_waytype='post';
		$scope.ajax(postdata,query,function(result){
			$scope.posting=false;
			if(!no_hold){
				$scope.page_loading('hide');
			}			
			if($.isFunction(callback)){
				callback(result);
			}else if(callback=='message'){
				//callback为message表示只返回消息提示，不进行其他操作
				$scope.message_json({'message':result,'type':'success'});
			}else if(callback=='ignore'){
				//callback为message表示只返回消息提示，不进行其他操作
				return true;
			}else{
				var ac=angular.copy($scope.page);
				ac.nohis=true;
				var msg={'message':result,'type':'success','action':ac};
				$scope.message_json(msg);
			}
		});
	}
	$scope.post_jyapi=function(postdata,query,callback,async,direct){
		$scope.ajax(postdata,query,callback,async,direct);
	}
	$scope.ajax=function(postdata,query,callback,async,direct){
		if(postdata && postdata.config_this){
			var config_this=postdata.config_this
		}else{
			var config_this=window.config.this
		}
		var url=window.config.siteroot+"api.php?i="+window.config.uniacid+"&this="+config_this+"&token="+window.config.token;
		if(query){
			url=url+'&'+query;
		}
		//是否同步，默认为异步
		if(!async){
			async=true;
		}else{
			async=false;
		}
		//来自兼容插件
		if(postdata.ismodule){
			postdata.m=postdata.plugin;
			postdata.do=postdata.action;
			postdata.action='module';
		}
		//console.log(url);
		$.ajax({
			url: url, type: "post", dataType: "json", timeout: "60000",async:async,
			data: postdata,
			success: function (result) {
				//console.log('收到ajax结果');console.log(postdata);console.log(result);
				if(direct && $.isFunction(callback)){
					callback(result);
					return true;
				}
				
				if(result.more){
					if(result.more.confirm && result.more.confirm.message){
						$scope.confirm(result.more.confirm);
						return true;
					}
					if(result.more.open_modal){
						$scope.access_modal(result.more.open_modal);
						return true;
					}
					$scope.set_more(result.more);
				}
				if(result.action || result.url){
					$scope.message_json(result);
				}else if(result.type=='success'){
					if($.isFunction(callback)){
						callback(result.message);
					}else{
						$scope.message(result.message,result.type);
					}
				}else{
					if(postdata.is_access && result.type=='error' && !result.action){
						//访问页面出错，如果上一页正常则跳转上一页，否则跳转首页
						if($scope.historys.length>0){
							$scope.goback();
						}else{
							/*var post={'plugin':'','action':''};
							post=angular.toJson(post);
							post=base64.encode(post,window.config.base_key_str);
							var pdata={'plugin':'core','action':'tools.session','postdata':post,'nosession':1};
							$scope.ajax(pdata,'',function(res){
								result.action='./index.php';
							},true);*/
						}
					}
					$scope.message_json(result);
					
				}
			},error: function (XMLHttpRequest, textStatus, errorThrown) {
				if(textStatus=='timeout'){
					$scope.message('请求超时！'+url,'error');
				}else{
					if(!XMLHttpRequest.responseText){
						return false;
						console.log('服务器没有返回数据！也许被防火墙拦截了，请查看拦截日志！');console.log(postdata);
					}
					$scope.message(XMLHttpRequest.responseText,'error');
				}
			}
		});
	}
	$scope.set_more=function(more){
		//console.log('more');console.log(more);
		//调整公众号信息
		if(more.account){
			$scope.main.account=more.account;
		}
		if(more.frames && more.merch_menu!=1 && typeof(more.frames)!='string'){
			$scope.frames='';
			$scope.framesdiy=more.frames;
		}
		//设置页面左侧菜单
		if(more.menu && Array.isArray(more.menu) && more.menu.length>0){
			console.log('设置左侧菜单');
			$scope.frames={'child':more.menu};
		}else{
			$scope.active_menu();
		}
		//设置页面tab，pc端生成页面专用
		if(more.tabs){
			$scope.main.tabs=more.tabs;
		}
		if(more.modaltabs){
			$scope.main.modaltabs=more.modaltabs;
		}
		if(more.top_plugin_menu){
			$scope.main.top_plugin_menu=more.top_plugin_menu;
		}
		if(more.basic_plugin){
			$scope.main.basic_plugin=more.basic_plugin;
		}
		//设置页面完整菜单
		if(more.framess && more.merch_menu!=1){
			if(typeof(more.framess)!='string'){
				$scope.framess.diy=more.framess;
				$scope.current_menu='diy';
			}else{
				if(!$scope.framess[more.framess]){
					//获取菜单
					var postdata={'plugin':'core','action':'tools.menu','op':'get','menu_name':more.framess};
					$scope.ajax(postdata,'',function(res){
						$scope.framess[more.framess]=res;
						$scope.$evalAsync();
						
					},true);
				}
				$scope.current_menu=more.framess;
			}
		}
		//设置页面标题
		if(more.title){
			if($scope.main.name){
				more.title += '-'+$scope.main.name
			}
			$scope.page.title=more.title;
			$(document).attr('title',more.title);
		}
		//设置页面关键词
		if(more.keywords){
			$scope.page.keywords=more.keywords;
			$("meta[name='keywords']").attr('content', more.keywords);
		}
		//设置页面描述
		if(more.description){
			$scope.page.description=more.description;
			$("meta[name='description']").attr('content', more.description);
		}
		//设置页面框架样式
		if(more.header && $scope.header!=more.header){
			$scope.header=more.header;
			window.wait_header_download=true;
		}		
	}
	$scope.in_array=function(v,arr){		
		var res=false;
		$.each(arr,function(i,d){
			if(d==v){
				res=true;
			}
		});
		return res;
	}
	$scope.made_page=function(htmlss,pagevalue){
		if(typeof(htmlss)!='object'){
			var page_html=$compile(htmlss)($scope);
			return page_html;
		}else{
			var page_html=made_page.made_page(htmlss,pagevalue);
			
			page_html=$compile(page_html)($scope);
			return page_html;
		}
	}
	
	$scope.ngcombile=function(html){
		return $compile(html)($scope);
	}
	//页面加载成功执行函数
	$scope.start=function(){
			//微信小程序加返回键
			if(window.config.fromh5wxapp==1){
				wx.miniProgram.getEnv(function(res) {
					if(window.history.length>1){
							scope.pagedata.history=window.history.length
							scope.pagedata.is_backpage=true
					}else{
							scope.pagedata.is_backpage=false
					}
				});
			}
			if(window.scope.main && window.scope.main.isapp==1){
				if(window.history.length>1){
					scope.pagedata.history=window.history.length
					scope.pagedata.is_backpage=true
				}else{
					scope.pagedata.is_backpage=false
				}
			}
			//代码编辑器
			if($('.edit_code').length>0){
					window.code_edit={};
					$('.edit_code').each(function(){
						var id=$(this).attr('id');
						var code=$(this).attr('data-code');
						window.code_edit[id]=window.ace.edit(id);
						window.code_edit[id].setTheme("ace/theme/xcode");
						window.code_edit[id].session.setMode("ace/mode/"+code);
						window.code_edit[id].setFontSize(16);
						window.code_edit[id].setValue($scope.pagedata.item[id]);
						var temp=function(){
							$scope.pagedata.item[id]=window.code_edit[id].getValue();
						}
						$scope.before_post.push(temp);
					});
			}
//滑块表单
			if($('.slider').length>0){
				require(['jquery.ui'],function(){
					$('.slider').each(function(){
						var min=$(this).attr('data-min');
						var max=$(this).attr('data-max');
						var model=$(this).attr('data-model');
						var def=$(this).attr('data-default');
						var step=$(this).attr('data-step');
						var orientation=$(this).attr('data-orientation');
						if(!model){
							return false;
						}
						if(!min){
							min=0;
						}else{
							min=parseInt(min);
						}
						if(!max){
							max=100;
						}else{
							max=parseInt(max);
						}
						if(!def){
							def=min;
						}else{
							def=parseInt(def);
						}
						
						if(!step){
							step=2;
						}else{
							step=parseInt(step);
						}
						var ops={
							slide:function(event,ui){
									eval('window.scope.'+model+'='+ui.value+';');
									window.scope.$evalAsync();
								},
							value:def,
							range:"min",
							min:min,
							max:max,
							step:step,
							
						};
						if(orientation){
							ops.orientation=orientation;
						}
						$(this).slider(ops);
					});
					
				});
			}
			//显示最终页面
			setTimeout(function(){
				$scope.page_loading('hide');
				$('#mainbody').show();
			},200);
			
	}
	$scope.gohome=function(action){
		scope.access_json(scope.main.menus[0].action || action);
	};
	$scope.goback=function(page_url,newpage){
		console.log('historys'+$scope.historys.length);
		if(!page_url && !newpage){
			if($scope.historys.length>0 || window.config.os=='windows'){
				window.history.go(-1);
			}else{
				window.history.go(-1);
				//$scope.closeWindow();
			}
			return;
		}
		if($scope.check_modal()){
			$scope.modalurl=false;
			window.bootstrap('.modal').modal('hide');
			return;
		}
		var temp;
		do{
			if($scope.historys.length<=0){
				if(newpage){
					$scope.access_json(newpage);
					return;
				}
				//此处直接返回上一页，如果上一页还是当前系统，即地址#前面的内容一致，则无法触发真实访问！
				if(window.config.os=='windows' || page_url){
					temp=JSON.parse(page_url);
				}else{
					temp=JSON.parse(page_url);
					//$scope.closeWindow();
					return;
				}
				break;
			}
			temp=$scope.historys.pop();
			if(temp.plugin==$scope.page.plugin && temp.action==$scope.page.action && temp.op==$scope.page.op && temp.query==$scope.page.query){
				
			}else{
				break;
			}
		}while(true);
		temp.nohis=true;
		$scope.access_json(temp);
	}
	$scope.closeWindow=function(){
		$scope.confirm({
			'message':'确认要退出页面？',
			'success':function(){
				$scope.closeWindowto();
			},
			'fail':function(){}
		});
		return;
	}
	$scope.closeWindowto=function(){
		console.log('closeWindowto');
		if(window.config.container=='wechat' && window.wx){
			wx.closeWindow();
		}else if(navigator.userAgent.indexOf('Firefox') !== -1 || navigator.userAgent.indexOf('Chrome') !== -1) {
          window.location.href = 'about:blank'
        } else {
          window.opener = null
          window.open('', '_self')
          window.close()
        }
		return;
	}
	$scope.goforward=function(page_url){
		if(!page_url){
			$scope.goback();
			return;
		}else{
			$scope.access_json(page_url);
		}
	}
	$scope.gowxhome=function(){
		wx.miniProgram.navigateTo({
			url: '/pages/index/index'
		})
	}
	$scope.previewImage=function(image,images){
		image=image?image:images[0];
		images=images?images:[image];
		 wx.previewImage({
			current: image,
			urls: images
		});
	}
	//消息提醒
	$scope.message_json=function(message){
		if(!message || typeof(message)!='object'){
			return false;
		}
		$scope.message(message.message,message.type,message.action,message.url);
	}
	$scope.message=function(msg,type,action,url){
		if($('#page-loading').is(":visible")){
			//隐藏加载动画
			$scope.page_loading('hide');
		}
		if($scope.posting){
			$scope.posting=false;
		}
		
		if(msg){
			if(type=='alert'){
				alert(msg);
				$scope.message(false,type,action,url);
				return;
			}
			if($('#msg-loading').length==0){
				$.get(window.config.siteroot+'core/resource/message.html?v='+window.config.urlargs,function(html){
					if($('#msg-loading').length==0){
						$('body').prepend(html);
					}
					$scope.message(msg,type,action,url);
				});
				return;
			}
			$('#msg-loading').children().children().text(msg);
			$('#msg-loading').show();
			$msgshowtime=type=='error'?2000:500;
			setTimeout(function(){
				$('#msg-loading').hide();
				$scope.message(false,type,action,url);
			},$msgshowtime);
		}else{
			
			if(action){
				if(action=='hold'){
					return true;
				}else if(action=='reload'){
					window.location.reload();
				}else if(action=='goback'){
					$scope.goback();
				}else if(action=='closeWindow'){
					wx.closeWindow();
				}else{
					if($('body').hasClass('modal-open')){
						if(msg!==false){
							$scope.access_modal(action);
						}else{
							window.bootstrap('#modal_content').modal('hide');
							$scope.access_json(action);
						}
					}else{
						$scope.access_json(action);
					}
				}
			}else if(url){
				if(window.config.os=='windows'){
					if($('body').hasClass('modal-open')){
						window.bootstrap('#modal_content').modal('hide');
					}
					if($('#open-window-modal').length<=0){
						$.get(window.config.siteroot+'core/resource/open.html?v='+window.config.urlargs,function(html){
							$('body').prepend(html);
							$('#open-window-modal').find('#openhref').click(function(){
								window.bootstrap('#open-window-modal').modal('hide');
							});
							$scope.message('',type,action,url);
						});
					}else{
						$('#open-window-modal').find('#openhref').attr('href',url);
						window.bootstrap('#open-window-modal').modal();
					}
				}else{
					window.location.href=url;  
				}
				
			}else if(type=='error'){
				throw SyntaxError('页面返回错误！');
			}else{
				if($('body').hasClass('modal-open')){
					window.bootstrap('#modal_content').modal('hide');
				}
			}
		}
		return true;
	}
	$scope.confirm=function(cf){
		//alert('准备弹出模态框');
		if($scope.posting){
			$scope.posting=false;
		}
		if($('#page-loading').is(":visible")){
			//隐藏加载动画
			$scope.page_loading('hide');
		}
		if(cf.fail_btn){
			cf.cancel_btn=cf.fail_btn;
		}
		if(cf.fail){
			cf.cancel=cf.fail;
		}
		$scope.tool.confirm_json(cf);
		/*$scope.modalurl=$scope.sys_html('common/confirm',true);
		$scope.modaldata={'no_head':true,'no_foot':true,'msg':cf.message,'success':cf.success,'fail':cf.fail,'success_btn':cf.success_btn,'fail_btn':cf.fail_btn,'title':cf.title};
		$scope.$evalAsync();
		window.bootstrap('#modal_content').modal();*/
	}
	//modal 相关
	$scope.modaldata={};
	$scope.modal='';
	$scope.modalurl='';
	$scope.modal_set='';
	$scope.modal_to='';
	$scope.modal_start=true;
	$scope.check_modal=function(){
		if($('body').hasClass('modal-open')){
			return true;
		}else{
			return false;
		}
	}
	$scope.modal_json=function(json){
		if(!json){
			return false;
		}
		if(typeof(json)!='object'){
			json=$scope.links(json,'',true);
		}
		if(json.action && !json.modal){
			json.modal=json.action;
		}
		
		$scope.getmodal(json.modal,json.op,json.query,json.html,json.plugin);
	}
	//兼容新型统一URL提交格式
	$scope.access_modal=function(json,query){
		if(typeof(json)=='string'){
			json=$scope.links(json,'',true);
		}
		if(query){
			json.query=query;
		}
		$scope.getmodal(json.action,json.op,json.query,'',json.plugin);
	}
	$scope.getmodal=function(modal,op,query,html,p){
		$scope.main.modaltabs=[];
		$('#modal_base_template_html').html('');
		if(modal && modal.indexOf('/')>=0){
			//统一URL格式的页面写法
			var url=$scope.links(modal,'',true);
			modal=url.action;
			op=url.op;
			p=url.plugin;
			query=url.query+'&'+query;
		}
		if(modal && $scope.modal !=modal){
			$scope.modal=modal;
		}
		if(p){
			$scope.modal_plugin=p;
		}else{
			if($('#modal_content').is(':hidden')){
				//初次从主页面进入modal页
				console.log('获取主页面的plugin');
				$scope.modal_plugin=$scope.page.plugin;
			}
		}
		if(!$scope.modal_plugin){
			$scope.modal_plugin=$scope.page.plugin;
		}
		if(!$scope.modal){
			$scope.modal=$scope.page.action;
		}
		if(!html){
			html=made_page.replace('.','/',$scope.modal);
		}
		
		var postdata={'plugin':$scope.modal_plugin,'action':$scope.modal,'is_modal':1};
		if(op){
			postdata.op=op;
		}
		//console.log('getmodal');console.log(postdata);
		$scope.ajax(postdata,query,function(data){			
			$scope.modaldata=data;
			//console.log('modal加载成功！');
			//如果是数据选择类型modal或额外数据编辑类型，此处读取当前值存入modaldata.item
			if(data.htmls && !data.item && (data.htmls.type=='list' || data.htmls.post=='modal_result')){
				//console.log('初始化modaldata.item的值！');
				//传的对象是数组
				if(Array.isArray($scope.modal_to)){
					for(var i=0;i<=$scope.modal_to.length;i++){
						if($.isFunction($scope.modal_set)){
							$scope.modaldata.item=$scope.modal_to[i];
						}else{
							if(data.htmls.result_field){
								$scope.modaldata.item={};
								$scope.modaldata.item[data.htmls.result_field]=$scope.modal_set[$scope.modal_to[i]];
							}else{
								$scope.modaldata.item=$scope.modal_set[$scope.modal_to[i]];
							}
						}
					}
				}else{
					if($.isFunction($scope.modal_set)){
							$scope.modaldata.item=$scope.modal_to;
					}else{
							if(data.htmls.result_field){
								$scope.modaldata.item={};
								$scope.modaldata.item[data.htmls.result_field]=$scope.modal_set[$scope.modal_to];
							}else{
								$scope.modaldata.item=$scope.modal_set[$scope.modal_to];
							}
					}
				}
			}
			if($scope.modaldata.htmls){
				if(typeof($scope.modaldata.htmls)=='string' && $scope.modaldata.htmls.slice(0,4)=='url:'){
					//后端指定页面文件地址
					$scope.modal_use_template=false;
					$scope.modalurl=$scope.modaldata.htmls.slice(4);
				}else{
					$scope.modal_use_template=true;
					if($scope.modaldata.htmls.type){
						$scope.modaldata.htmls=[$scope.modaldata.htmls];
					}
					if($scope.modaldata.htmls[0] && $scope.modaldata.htmls[0].tabs){
						$scope.main.modaltabs=$scope.modaldata.htmls[0].tabs;
					}
					var page_html=$scope.made_page($scope.modaldata.htmls,'modaldata');
					$('#modal_base_template_html').html(page_html);
					$scope.start();
				}
				
				
			}else{
				$scope.modal_use_template=false;
				if(html){
					$scope.modalurl=$scope.modal_html(html);
				}
			}
			$scope.$evalAsync();
			if($('#modal_content').is(':hidden')){
				window.bootstrap('#modal_content').modal();
			}
		});
	}
	
	$scope.modal_func=function(data,to,modal,op,plugin,query){
		$scope.modal_start=false;
		if(modal && modal.indexOf('/')>=0){
			//统一URL格式的页面写法
			var url=$scope.links(modal,'',true);
			modal=url.action;
			op=url.op;
			plugin=url.plugin;
			query=url.query;
		}
		
		if(!modal){
			modal=$scope.page.action;
		}
		if(!plugin){
			plugin=$scope.page.plugin;
		}
		if(modal){
			$scope.modal_set=data;
			$scope.modal_to=to;
			$scope.getmodal(modal,op,query,'',plugin);
		}else{
			alert('modal参数错误！');
			return false;
		}
	}
	//thumb视频封面
	$scope.modal_result=function(data,title,isadd,thumb){
		//传的是对象
		if(Array.isArray(data) && Array.isArray($scope.modal_to)){
			for(var i=0;i<=$scope.modal_to.length;i++){
				if($.isFunction($scope.modal_set)){
					if($scope.modal_to[i]){
						$scope.modal_set(data[i],$scope.modal_to[i]);
					}else{
						$scope.modal_set(data[i]);
					}
				}else{
					if(Array.isArray($scope.modal_set[$scope.modal_to[i]])){
						if(Array.isArray(data[i])){
							data[i].forEach(function(v){
								if(v){
									$scope.modal_set[$scope.modal_to[i]].push(v);
								}
							});
						}else{
							$scope.modal_set[$scope.modal_to[i]].push(data[i]);
						}
					}else{
						$scope.modal_set[$scope.modal_to[i]]=data[i];
						if(title){
							$scope.choose_titles[$scope.modal_to[i]]=title;
						}
					}				
				}
			}
		}else{
			if($.isFunction($scope.modal_set)){
				if($scope.modal_to){
					$scope.modal_set(data,$scope.modal_to);
				}else{
					$scope.modal_set(data);
				}
			}else{
				if(Array.isArray($scope.modal_set[$scope.modal_to])){
					if(Array.isArray(data)){
						data.forEach(function(v){
							if(v){
								$scope.modal_set[$scope.modal_to].push(v);
							}
						});
					}else{
						$scope.modal_set[$scope.modal_to].push(data);
					}
				}else{
					if(Array.isArray(data) && data[0]){
						data=data[0];
					}
					if(isadd){
						$scope.modal_set[$scope.modal_to] +=data;
					}else{
						$scope.modal_set[$scope.modal_to]=data;
					}
					if(title){
						$scope.choose_titles[$scope.modal_to]=title;
					}
					if(thumb){
						$scope.modal_set.thumb=thumb;
					}
				}
			}
		}
		$scope.modalurl=false;
		window.bootstrap('#modal_content').modal("hide");
	}
	$scope.links=function(paop,query,ismodal){
		if(paop.slice(0,4)=='http' || paop.slice(0,11)=='./index.php'){
			return paop;
		}
		paop=paop.split('/');
		if(ismodal){
			var newpage={}
		}else{
			var newpage=scope.page
		}
		var num=paop.length;
		switch(num){
			case 4:
				var params={'plugin':paop['0']?paop['0']:newpage.plugin,'action':paop['1']?paop['1']:newpage.action,'op':paop['2'],'query':paop['3']};
				break;
			case 3:
				var params={'plugin':paop['0']?paop['0']:newpage.plugin,'action':paop['1']?paop['1']:newpage.action,'op':paop['2']};
				break;
			case 2:
				var params={'plugin':newpage.plugin?newpage.plugin:'','action':paop['0'],'op':paop['1']};
				break;
			case 1:
				var params={'plugin':newpage.plugin?newpage.plugin:'','action':newpage.action?newpage.action:'','op':paop['0']};
				break;
			default:
				var params={};
		}
		if(query){
			if(params.query){
				params.query=params.query+'&'+query;
			}else{
				params.query=query;
			}
		}
		if(params.query && params.query.indexOf('=')<0){
			params.query=base64.decode(params.query,window.config.default_base64_key);
		}
		return params;
	}
	//生成二维码
	$scope.qrcode=function(value,field,id,width){
		if(!id){
			id='qrcode-'+field;
		}
		if(!value[field]){
			return false;
		}
		require(['jquery.qrcode'], function(){
			var url = value[field];
			setTimeout(function(){$('#'+id).html('').qrcode({
				render: 'canvas',
				width: width && width!='{width}'?width:150,
				height: width && width!='{width}'?width:150,
				text: url
			});},200);
		});
	}
	$scope.date=function(time,nosec,onday){
		if(!time || time==0){
			return '';
		}
		var myDate=new Date();
		myDate.setTime(time*1000);
		var year=myDate.getFullYear();
		var month=myDate.getMonth();
		month+=1;
		if(month<10){
			month='0'+month;
		}
		var day=myDate.getDate();
		if(day<10){
			day='0'+day;
		}
		var hour=myDate.getHours();
		if(hour<10){
			hour='0'+hour;
		}
		var min=myDate.getMinutes();
		if(min<10){
			min='0'+min;
		}
		var sec=myDate.getSeconds();
		if(sec<10){
			sec='0'+sec;
		}
		if(onday){
			return year+'-'+month+'-'+day;
		}
		if(nosec){
			return year+'-'+month+'-'+day+' '+hour+':'+min;
		}
		return year+'/'+month+'/'+day+' '+hour+':'+min+':'+sec;
	}
	$scope.duoxuans=function(value,to,field){
		if(to[field]==undefined || to[field]=='' || !to[field]){
			to[field]=';';
		}
		if(to[field].indexOf(';'+value+';')<0){
			to[field]=to[field]+value+';';
		}else{
			to[field]=to[field].replace(';'+value+';',';');
			if(to[field]==';'){
				to[field]='';
			}
		}
	}
	$scope.ifelse=function(check,tru,fals){
		if(check){
			return tru;
		}else{
			return fals;
		}
	}
	$scope.choose_source= function(tovalue,field,type){//选择附件
		if(window.config.this=='custom'){
			$scope.modal_func(tovalue,field,'tools.choose_file','','core','source_type='+type+'&type=one');
		}else{
			$scope.modal_func(tovalue,field,'tools.choose_source','','core','source_type='+type+'&type=one');
		}
    }
	$scope.wechat_image=function(to,field){
		//先调用图片选择接口获得 localId ，然后调用图片上传接口获得 serverId ，再调用系统图片上传接口获得图片路径
		var parm={count:1};
		parm.success=function(res){			
			var upload={'localId':res.localIds[0]};
			upload.success=function(res){
				var post={'plugin':'core','action':'tools.file_upload','op':'wechat_image','nosession':1,'serverid':res.serverId};
				$scope.ajax(post,'',function(result){
					$scope.return_value(result,to,field);
					$scope.$evalAsync();
				});
			}
			wx.uploadImage(upload);
		}
		wx.chooseImage(parm);
	}
	$scope.image= function(tovalue,field){//特殊传值方式图片上传
		if(window.config.this=='manage'){
			$scope.modal_func(tovalue,field,'tools.choose_source','','core','source_type=image&type=one');
		}else{
			$scope.modal_func(tovalue,field,'tools.choose_file','','core','source_type=image&type=one');
		}
    }
	$scope.images= function(tovalue,field,nomodal){	
		if(window.config.this=='manage'){
			var res=function(result){
				if(result && result!=';'){					
					result=result.split(';');
					if(typeof(tovalue)=='function'){
						tovalue(result,field);
						return;
					}else if(typeof(tovalue[field])!='object'){
						tovalue[field]=[];
					}
					$.each(result,function(index,attachment){
						if(attachment && !$scope.in_array(attachment,tovalue[field])){
							tovalue[field].push(attachment);
						}
					});
				}
			}
			$scope.modal_func(res,'','tools.choose_source','','core','source_type=image&type=more');
		}else if(window.config.container=='wechat' && wx && wx.chooseImage && window.jssdkconfig.appId && false){//微信接口多图上传存在问题，暂不使用
			var parm={};
			parm.success=function(res){
				$scope.page_loading();
				$scope.upload_wechat_image(res.localIds,function(result_list){
					result_list.forEach(function(value){
						tovalue[field].push(value);
					});
					$scope.$evalAsync();
					$scope.page_loading('hide');
				});
			}
			wx.chooseImage(parm);
		}else if(nomodal){
			$scope.up_file(function(res){
				if(typeof(tovalue)=='function'){
					tovalue(res,field);
					return;
				}
				if(typeof(tovalue[field])!='object'){
					tovalue[field]=[];
				}
				res.forEach(function(value){
					tovalue[field].push(value);
				});
			},'','image',true);
		}else{
			var res=function(result){
				if(result && result!=';'){					
					result=result.split(';');
					if(typeof(tovalue)=='function'){
						tovalue(result,field);
						return;
					}else if(typeof(tovalue[field])!='object'){
						tovalue[field]=[];
					}
					$.each(result,function(index,attachment){
						if(attachment && !$scope.in_array(attachment,tovalue[field])){
							tovalue[field].push(attachment);
						}
					});
				}
			}
			$scope.modal_func(res,'','tools.choose_file','','core','source_type=image&type=more');
		}
	}
	$scope.upload_wechat_image=function(localIds,callback,result_list){
		if(!result_list){
			result_list=[];
		}
		if(localIds.length<=0){
			callback(result_list);
			return;
		}
		var localid=localIds.pop();
		wx.uploadImage({
			isShowProgressTips:0,
			localId:localid,
			success:function(res){
				var post={'plugin':'core','action':'file','op':'wechat_image','nosession':1,'serverid':res.serverId};
				$scope.ajax(post,'',function(attachment){
					result_list.push(attachment);
					$scope.upload_wechat_image(localIds,callback,result_list);
				});
			},
		});
	}
	$scope.time_one=function(tovalue,field,id,time_type){		
		require(["datetimepicker"], function(){
			var fmt;
			if(time_type=='day'){
				fmt="Y-m-d";
			}else if(time_type=='year'){
				fmt="Y";
			}else{
				fmt="Y-m-d H:i";
			}
			var option = {
				lang : "zh",
				step : 5,
				timepicker : true,
				closeOnDateSelect : true,
				format : fmt,
				onChangeDateTime: function(dateText, inst) {
					tovalue[field]=$("#"+id).val();
					//var date=new Date(dateText);
					//tovalue[field]=parseInt(date.getTime()/1000);
				}
			};
			$("#"+id).datetimepicker(option);
		});
	}
	$scope.time_range=function(to,field,id,read,no_time_pic){
		//console.log('触发time_range');console.log(id);
		
		require(["daterangepicker"], function($){
				$("#"+id).each(function(){
					var elm = this;
					var dt=new Date();
					var date_str=$scope.date(parseInt(dt.getTime()/1000),true);
					date_str=date_str.split(' ')[0];
					var start_Date=date_str+' 00:00';
					var end_Date=date_str+' 23:59';
					start_Date='';end_Date='';
					var startDate=new Date();var endDate=new Date();
					if(to[field]){
						if(to[field].tstart){
							start_Date=$scope.date(to[field].tstart,true);
							startDate=new Date(to[field].tstart * 1000);
						}
						if(to[field].tend){
							end_Date=$scope.date(to[field].tend,true);
							endDate=new Date(to[field].tend * 1000);
						}
					}
					if(start_Date || end_Date){
						$(elm).find(".date-title").html(start_Date + " 至 " + end_Date);
					}else{
						$(elm).find(".date-title").html("点击设置时间段");
					}
					
					$(this).daterangepicker({
						startDate: startDate,
						endDate: endDate,
						timePicker:no_time_pic?false:true,
						timePickerIncrement:5,
						timePicker12Hour:false,
					}, function(start, end){
						$(elm).find(".date-title").html(start.toDateTimeStr() + " 至 " + end.toDateTimeStr());
						to[field]={'tstart':start.unix(),'tend':end.unix()};
						$scope.$evalAsync();
					});
				});
		});
	}
	$scope.code_image=function(id,init){
		if(init){
			var time = 500
		}else{
			var time = 10
		}
		setTimeout(function(){
			var url=window.config.siteroot+'api.php?this='+window.config.this+'&token='+window.config.token+'&plugin=core&action=tools.code&v='+Math.ceil(Math.random() * 10000);
			if(id){
				$('#'+id).attr('src',url);
			}else{
				return url;
			}
		},time);
	}
	$scope.showday=function(year,month,day){
		var months=[4,6,9,11];
		if($.inArray(month,months)>=0 && day==31){
			return false;
		}
		if(month==2 && day>29){
			return false;
		}
		if(month==2 && (year%4) && day>28){
			return false;
		}
		return true;
	}
	$scope.checkarray=function(data,v){
		if(!data[v] || !Array.isArray(data[v])){
			data[v]=[];
		}
	}
	$scope.checkobj=function(data,v){
		if(!data[v] || typeof(data[v]) != 'object' || Array.isArray(data[v])){
			data[v]={};
		}
	}
	$scope.check_show=function(item,show){
		if(!item || typeof(item)!='object' || !show){
			return false;
		}
		if(typeof(show)!='object'){
			return item[show];
		}
		if(show['0']){
			if(show['2']){
				eval("var res=$scope."+show['2']+"=='"+show['1']+"';");
				return res;
			}
			if(typeof(show['1'])=='object'){
				return $scope.in_array(item[show['0']],show['1']);
			}
			if(item[show['0']]==show['1']){
				return true;
			}
			return false;
		}
		var res=true;
		var ops=['<','>','<=','>=','!='];
		$.each(show,function(key,value){
			if(typeof(value)=='object'){
				if(!$scope.in_array(item[key],value)){
					res=false;
				}
			}else if(key.indexOf(' ')>0){
				//操作符
				var temp=key.split(' ');
				if($scope.in_array(temp['1'],ops)){
					eval("var check=item[temp['0']] "+temp['1']+" value;");
					if(!check){
						res=false;
					}
				}
			}else{
				if(item[key]!=value){
					res=false;
				}
			}
		});
		return res;
	}
	$scope.count_down=function(num,id,text_count,text_end,start_time){
		if(!start_time){
			start_time=$scope.page.time;
		}
		if(start_time!=$scope.page.time){
			return false;
		}
		if(num>0){
			$('#'+id).text(num+text_count);
			num=num-1;
			setTimeout(function(){$scope.count_down(num,id,text_count,text_end,start_time);},1000);
		}else{
			if($.isFunction(text_end)){
				text_end();
			}else{
				$('#'+id).text(text_end);
			}
		}
	}
	$scope.clip=function(data){
		$('#copy-data').attr('data-clip',data);
		$('#copy-data').click();
	}
	$scope.up_file=function(tovalue,field,type,multiple,process,group_id,group_id2){
		if(false && !multiple && type=='image' && window.config.this=='custom' && window.config.container=='wechat' && wx && wx.uploadImage && window.jssdkconfig.appId){
			$scope.wechat_image(tovalue,field);
		}else{
			var newfield=[];
			if(typeof(field)=='string'){
				newfield[0]=field;
			}else{
				newfield=field;
			}
			$scope.tool.up_file(type,function(res,thumb){
				$scope.return_value(res,tovalue,newfield[0]);
				if(newfield[1]){
					$scope.return_value(thumb,tovalue,newfield[1]);
				}
				$scope.$evalAsync();
			},multiple,'',process,group_id,group_id2);
		}
	}
	$scope.trust=function(html){
		if(!html){
			html='<div></div>';
		}
		return $sce.trustAsHtml(html);
	}
	$scope.trust_url=function(url){
		if(!url){
			return false;
		}
		return $sce.trustAsResourceUrl(url);
	}
	$scope.scroll=function(callback,type,id){
		//console.log('收到注册滚动事件请求~');
		if(!$.isFunction(callback)){
			return false;
		}
		
		if(id){
			//console.log('注册标签滚动事件~');
			$('#'+id).scroll(function(){
				//console.log('标签滚动事件~');
				var the=$(this),
				 viewH =$(this).height(),//可见高度
				 contentH =$(this).get(0).offsetHeight,//内容高度
				 scrollTop =$(this).scrollTop();//滚动高度
				 if(!type){
					if(contentH<=viewH+scrollTop){
						 callback();
					 }
				 }else{
					 if(scrollTop==0){
						 callback();
					 }
				 }
				 
			});
		}else{
			//console.log('注册屏幕滚动事件~');
			$(window).scroll(function(){
				//console.log('屏幕滚动事件~');
				var the=$(this),
				 viewH =$(this).height(),//可见高度
				 contentH =$(document).height(),//内容高度
				 scrollTop =parseInt($(this).scrollTop());//滚动高度
				
				 if(!type){
					if(contentH<=viewH+scrollTop){
						 callback();
					 }
				 }else{
					 if(scrollTop==0){
						 callback();
					 }
				 }
				 
			});
		}
	}
	$scope.str_json=function(str){
		if(!str || typeof(str)!='string'){
			return {};
		}
		return JSON.parse(str);
	}
	$scope.json_str=function(json){
		if(!json || typeof(json)!='object'){
			return '';
		}
		return JSON.stringify(json);
	}
	$scope.export=function(url,params){
		var param=angular.copy(params);
		url=$scope.links(url);
		url.plugin=url.plugin || $scope.page.plugin;
		url.action=url.action || $scope.page.action;
		if(typeof(param)=='object'){
			param=$scope.made_query(param);
		}
		if(url.query){
			url.query+='&';
			
			url.query+=param;
		}else{
			url.query=param;
		}
		var res=window.config.siteroot+'api.php?this='+window.config.this+'&token='+window.config.token+'&plugin='+url.plugin+'&action='+url.action+'&op='+url.op+'&'+url.query;
		return res;
	}
	$scope.get_hash=function(hash){
		var access_json={'query':''};
		var params=hash.split('&');
		params.forEach(function(value){
			var temp=value.split('=');
			if(temp.length<2){
				return;
			}
			if(temp[0]=='plugin'){
				access_json.plugin=temp[1];
			}else if(temp[0]=='action'){
				access_json.action=temp[1];
			}else if(temp[0]=='op'){
				access_json.op=temp[1];
			}else{
				access_json.query+=value+'&';
			}
		});
		return access_json;
	}
	$scope.replace=function(search,replace,str){
		if(!str){
			return '';
		}
		if(search==replace){
			return str;
		}
		res=str.replace(search,replace);
		if(res!=str){
			res=$scope.replace(search,replace,res);
		}
		return res;
	}
	$scope.location=function(callback,type,noget,isup){
		$scope.tool.location(callback,type,noget,isup);
	}
	$scope.pay_submit=function(data,submit_url,complete_url,fail_url,onemerchid,params){
		$scope.post_json(submit_url,data,function(pay_id){
			$scope.tool.pay(pay_id,function(res){
				fail_url=fail_url?fail_url:complete_url;
				if(res.type=='success'){
					$scope.message('支付成功！','success',complete_url);
				}else{
					$scope.message('支付失败！','success',fail_url);
				}
			},'','',complete_url,fail_url,onemerchid,params);
		});
	}
	$scope.choose_link=function(obj,key,type,url,webid){
		type=type || 'url';
		if(type=='manage'){
			url=url || 'core/tools.manage_link/';
		}else{
			url=url || 'core/tools.link/';
		}
		$scope.modal_func(function(res){
			if(type=='url'){
				res=tool.custom_url(res);
			}else if(type=='allurl'){
				res=tool.custom_url(res,true);
			}
			if(webid){
				var paop=res.split('/');
				if(paop['3']){
					res=res+'&link_webid='+webid
				}else{
					paop['2']=paop['2']?paop['2']:'';
					var newlink=paop['0']+'/'+paop['1']+'/'+paop['2']+'/'
					res=newlink+'&link_webid='+webid
				}
				
			}
			obj[key]=res;
		},'',url);
	}
	$scope.price=function(fee){
		fee=fee?fee:0;
		return parseFloat(fee).toFixed(2);
		//fee=parseInt(fee)/100;
		//return fee+'元';
	}
	$scope.pcd=function(iscity){
		iscity=iscity?iscity:'';
		if($scope.pcd_data || $scope.pcd_loading){
			return;
		}
		$scope.pcd_loading=true;
		$scope.get_data(function(res){
			$scope.pcd_data=res;
			$scope.pcd_loading=false;
			$scope.$evalAsync();
		},'','core/tools.pcd//iscity='+iscity);
	}
	$scope.area_choose=function(){
		$scope.get_data(function(res){
			$scope.default_area=res.location;
			$scope.area_data=res.area_data;
		},'','core/tools.area/');
	}
	$scope.return_value=function(value,obj,field){
		var type=typeof(obj);
		if(type=='function'){
			obj(value,field);
		}else if(type=='object' && field){
			obj[field]=value;
		}else{
			console.log('传值失败，参数错误！');
		}
	}
	//获取多选选中的个数
	$scope.checkbox_num=function(str){
		if(!str){
			return 0;
		}
		return str.split(';').length-2;
	}
	$scope.check_form=function(id){
		//console.log('check_form');
		var message;var focus_input;
		if(id){
			$('#'+id).find('.must_set').each(function(){
				var fm=this;
				if(!$(fm).is(':visible')){
					return;
				}
				if(!$(fm).val()){
					if(!message){
						message=$(fm).next().text();
					}
					if(!focus_input){
						focus_input=true;
						$(fm).focus();
					}
					$(fm).nextAll().find('.help-block').show();
					$(fm).css('border-color','red');
				};
			});
		}else{
			$('.must_set').each(function(){
				var fm=this;
				if(!$(fm).is(':visible')){
					return;
				}
				if(!$(fm).val()){
					if(!message){
						message=$(fm).next().text();
					}
					if(!focus_input){
						focus_input=true;
						$(fm).focus();
					}
					$(fm).nextAll().find('.help-block').show();
					$(fm).css('border-color','red');
				};
			});
		}
		if(message){
			console.log('check_form');console.log(message);
			$scope.message(message);
			throw SyntaxError('页面返回错误！');
		}
	}
	window.scope=$scope;
	if(window.config.close_one_page){
		if(window.config.os=='windows' || true){//手机端、pc端都有header
				window.wait_header_download=true;
				if(window.config.username && $scope.main.framess){
					//登陆
					$scope.header='common/header';
					$scope.frames=$scope.main.framess[0];
				}else{
					$scope.header='common/header-cms';
				}
		}
		$scope.plugin_resource=window.config.siteroot+'addons/'+window.config.access_json.plugin+'/resource/';
		$scope.page=window.config.access_json;
		$scope.pagedata=window.config.main.pagedata;
		if(typeof($scope.pagedata.htmls)=='string' && $scope.pagedata.htmls.slice(0,4)=='url:'){
			$scope.use_template=false;
			$scope.main.page=$scope.pagedata.htmls.slice(4);
		}else{
			$scope.use_template=true;
			if($scope.pagedata.htmls.type){
				$scope.pagedata.htmls=[$scope.pagedata.htmls];
			}
			if(typeof($scope.pagedata.htmls[0])=='object' && $scope.pagedata.htmls[0]['tabs']){
				$scope.main.tabs=$scope.pagedata.htmls[0]['tabs'];
			}
			$scope.insert_html($scope.made_page($scope.pagedata.htmls,'pagedata'));
			
			
		}
		if($scope.pagedata.sharedata){
			if($scope.pagedata.sharedata){
				if(!window.sharedata){
					window.sharedata={};
				}
				if($scope.pagedata.sharedata.title){
					window.sharedata.title=$scope.pagedata.sharedata.title;
				}
				if($scope.pagedata.sharedata.link){
					window.sharedata.link=$scope.pagedata.sharedata.link;
				}
				if($scope.pagedata.sharedata.desc){
					window.sharedata.desc=$scope.pagedata.sharedata.desc;
				}
				if($scope.pagedata.sharedata.imgUrl){
					window.sharedata.imgUrl=$scope.pagedata.sharedata.imgUrl;
				}
			}
		}
		$scope.$evalAsync();
	}else{
		var whash=window.location.hash;
		whash=decodeURIComponent(whash);
		var hash=whash.indexOf('page/');
		if(hash>0){
			hash=whash.slice(hash+5);
			var access_json=$scope.get_hash(hash);
		}else{
			var access_json=window.config.access_json;
		}
		if(!access_json.plugin || !access_json.action){
			access_json=window.config.access_json;
		}
		access_json.nohis=true;
		if(access_json.submit){
			$scope.post({},access_json.jy_links,'','','','','','',access_json.ismodule);
		}else{
			$scope.access_json(access_json);
		}
	}
	});
}]);
//整理提交数据
function clone(myObj){
    if(typeof(myObj) != 'object' || myObj == null) return myObj;
        var newObj = new Object();
        for(var i in myObj){
            newObj[i] = clone(myObj[i]);
        }
        return newObj;
}
if(!window.config.close_one_page){
	//单页访问模式下监听浏览器返回事件
	window.onpopstate=function(e){
		if(e.state==null || !e.state.page_url){
			return false;
		}
		window.scope.goback(e.state.page_url);
		return false;
	};
}else{
	var browserRule = /^.*((iPhone)|(iPad)|(Safari))+.*$/;
    if (browserRule.test(navigator.userAgent)) {
        window.onpageshow = function(event) {
            if (event.persisted) {
                window.location.reload()
            }
        };
    }

}
/*
	本代码用于解决苹果手机返回不刷新的问题，暂时不启用
	var browserRule = /^.*((iPhone)|(iPad)|(Safari))+.*$/;
    if (browserRule.test(navigator.userAgent)) {
        window.onpageshow = function(event) {
            if (event.persisted) {
                window.location.reload()
            }
        };
    }
*/

window.addEventListener('scroll', function () {
	//滑到底端事件
	if(window.scope.access_ing){
		//页面加载中时，不触发相应事件，以免页面加载过程中出现异常！
		return;
	}
	var viewH =$(window).height(),//可见高度
	contentH =$(document).height(),//内容高度
	scrollTop =$(window).scrollTop();//滚动高度
	if(typeof(window.scope.pagedata.scroll_bottom)=='function' && contentH<=viewH+scrollTop+1){
		window.scope.pagedata.scroll_bottom();
	}
	if(scrollTop==0 && typeof(window.scope.pagedata.scroll_top)=='function'){
		window.scope.pagedata.scroll_top();
	}
});
window.play_audio=function(ad){
	var audio=$(ad)[0];
	if(audio.ended || audio.paused){
		audio.play();
	}else{
		audio.pause();
	}
	
}
$(function(){
	$('.clip').each(function(){
		//console.log('初始化复制功能！');
		var elm=this;
		require(['clipboard'], function(t){
			$('#modal_content').removeAttr('tabindex');
			var c=new t(elm,{text:function(){
				var r=$(elm).attr('data-clip');
				return r;
			}});
			c.on('success',function(res){
				alert('复制成功！');
			});
		});
	});
});

require(['bootstrap'],function($){
	window.bootstrap=$;
});
